/*******************************************************************************
 * FeedbackManagerAction.java
 *
 * Created by Ashutosh
 * Last modified Date: Nov 13, 2008 5:14:32 PM by nishan
  * Version : 0.1
 * Copyright (c) 2008 - 2009 cyberThink Infotech Pvt. Ltd., All rights reserved.
 ******************************************************************************/

package com.printeverywhere.action;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.apache.struts2.interceptor.ServletRequestAware;

import com.printeverywhere.delegator.CommonFunctionDelegator;
import com.printeverywhere.delegator.FeedbackServiceDelegator;
import com.printeverywhere.delegator.UserServiceDelegator;
import com.printeverywhere.dto.Feedback;
import com.printeverywhere.dto.Items;
import com.printeverywhere.dto.User;
import com.printeverywhere.dto.UserFeedbackCount;
import com.printeverywhere.util.SearchCriteria;

/**
 * The Class FeedbackManagerAction.
 */
public class FeedbackManagerAction extends AdminEngineManagement implements ServletRequestAware {

	/** Logger for this class. */
	private static final Logger logger = Logger.getLogger(FeedbackManagerAction.class);

	/** The Constant serialVersionUID. */
	private static final long serialVersionUID = 1L;

	/** The item id. */
	private Integer itemId;

	/** The user id. */
	private String userId;

	/** The feedback id. */
	private int feedbackId;

	/** The buyer comment. */
	private String buyerComment = "";

	/** The seller comment. */
	private String sellerComment = "";

	/** The request. */
	private HttpServletRequest request;

	List<UserFeedbackCount> feedbackCountList = new ArrayList<UserFeedbackCount>();

	/* (non-Javadoc)
	 * @see com.opensymphony.xwork2.ActionSupport#execute()
	 */
	public String execute() throws Exception {
		if (logger.isDebugEnabled()) {
			logger.debug("execute() - start"); //$NON-NLS-1$
		}

		populateUserCountList();

		if (logger.isDebugEnabled()) {
			logger.debug("execute() - end"); //$NON-NLS-1$
		}
		return SUCCESS;
	}

	public void populateUserCountList() throws Exception {

		List userFeedbackCountList = CommonFunctionDelegator.executeSQLQuery("SELECT u.userID, u.email, count(f.positive), count(f.negative), count(f.neutral) FROM User u, Feedback f where u.id = f.from_user_id group by userId");

		for (Object object : userFeedbackCountList) {
			Object[] objectArray = (Object[]) object;
			UserFeedbackCount userFeedbackCount = new UserFeedbackCount();
			userFeedbackCount.setAccount(objectArray[0].toString());
			userFeedbackCount.setEmail(objectArray[1].toString());
			userFeedbackCount.setPositive(objectArray[2].toString());
			userFeedbackCount.setNegative(objectArray[3].toString());
			userFeedbackCount.setNeutral(objectArray[4].toString());
			feedbackCountList.add(userFeedbackCount);
		}
	}

	/**
	 * Search feedback.
	 *
	 * @return the string
	 */
	public String searchFeedback() throws Exception {
		if (logger.isDebugEnabled()) {
			logger.debug("searchFeedback() - start"); //$NON-NLS-1$
		}

		populateUserCountList();

		if(request.getParameter("saveComment") != null && request.getParameter("saveComment").equalsIgnoreCase("saveComment")){
			updateFeedback();
		}

		if(itemId == null || itemId < 1){
			addActionMessage("Enter valid Item Id");
			return INPUT;
		} else if(userId.equals("")){
			addActionMessage("Enter valid User Id");
			return INPUT;
		}

		User user = UserServiceDelegator.getUserByUserId(userId);

		if(user == null){
			addActionMessage("User not found please try another");
			return INPUT;
		}

		if (user.getId() != null) {
			SearchCriteria searchCriteria = new SearchCriteria();
			searchCriteria.setAttribute("itemId", itemId);
			List<Items> items = (List<Items>) CommonFunctionDelegator.getObjectBySearchCriteria(searchCriteria, Items.class);

			if(items.size() ==0){
				addActionMessage("Iteam not found please try another");
				return INPUT;
			}

			searchCriteria.removeAllAttribute();
			searchCriteria.setAttribute("itemId", items.size() > 0 ? items.get(0) : null);
			searchCriteria.setAttribute("userByFromUserId", user);

			Feedback listFeedback = FeedbackServiceDelegator
					.getFeedbackByUserItemId(searchCriteria);

			this.buyerComment = "";
			this.sellerComment = "";

			if (listFeedback.getId() != null) {
				if (listFeedback.getUserType().equalsIgnoreCase("B")) {
					this.buyerComment = listFeedback.getMessage();
				} else {
					this.sellerComment = listFeedback.getMessage();
				}
				this.feedbackId = listFeedback.getId();
			} else {
				addActionError("Record not found...");
			}
		} else {
			addActionError("User not found...");
		}

		if (logger.isDebugEnabled()) {
			logger.debug("searchFeedback() - end"); //$NON-NLS-1$
		}
		return SUCCESS;
	}

	/**
	 * Update feedback.
	 *
	 * @return the string
	 */
	public String updateFeedback() {
		if (logger.isDebugEnabled()) {
			logger.debug("updateFeedback() - start"); //$NON-NLS-1$
		}

		SearchCriteria searchCriteria = new SearchCriteria();
		searchCriteria.setAttribute("id", feedbackId);
		Feedback feedback = FeedbackServiceDelegator.getFeedbackListByUserId(
				searchCriteria).get(0);

		if (feedback.getUserType().equalsIgnoreCase("B")) {
			feedback.setMessage(this.buyerComment);
		} else {
			feedback.setMessage(this.sellerComment);
		}

		FeedbackServiceDelegator.updateFeedback(feedback);

		if (logger.isDebugEnabled()) {
			logger.debug("updateFeedback() - end"); //$NON-NLS-1$
		}
		return SUCCESS;
	}

	@Override
	public void validate() {
		this.buyerComment = "";
		this.sellerComment = "";
		super.validate();
	}

	public Integer getItemId() {
		return itemId;
	}

	public void setItemId(Integer itemId) {
		this.itemId = itemId;
	}

	/**
	 * Gets the user id.
	 *
	 * @return the user id
	 */
	public String getUserId() {
		return userId;
	}

	/**
	 * Sets the user id.
	 *
	 * @param userId the new user id
	 */
	public void setUserId(String userId) {
		this.userId = userId;
	}

	/**
	 * Gets the buyer comment.
	 *
	 * @return the buyer comment
	 */
	public String getBuyerComment() {
		return buyerComment;
	}

	/**
	 * Sets the buyer comment.
	 *
	 * @param buyerComment the new buyer comment
	 */
	public void setBuyerComment(String buyerComment) {
		this.buyerComment = buyerComment;
	}

	/**
	 * Gets the seller comment.
	 *
	 * @return the seller comment
	 */
	public String getSellerComment() {
		return sellerComment;
	}

	/**
	 * Sets the seller comment.
	 *
	 * @param sellerComment the new seller comment
	 */
	public void setSellerComment(String sellerComment) {
		this.sellerComment = sellerComment;
	}

	/**
	 * Gets the feedback id.
	 *
	 * @return the feedback id
	 */
	public int getFeedbackId() {
		return feedbackId;
	}

	/**
	 * Sets the feedback id.
	 *
	 * @param feedbackId the new feedback id
	 */
	public void setFeedbackId(int feedbackId) {
		this.feedbackId = feedbackId;
	}

	public void setServletRequest(HttpServletRequest request) {
		this.request = request;
	}

	/**
	 * @return the feedbackCountList
	 */
	public List<UserFeedbackCount> getFeedbackCountList() {
		return feedbackCountList;
	}

	/**
	 * @param feedbackCountList the feedbackCountList to set
	 */
	public void setFeedbackCountList(List<UserFeedbackCount> feedbackCountList) {
		this.feedbackCountList = feedbackCountList;
	}
}